package LinkStack;

import SingleLinkList.MyNode;

public class Stack<T> {
	private MyNode<T> head;
	private MyNode<T> top;
	private int size;
	
	{
		head=new MyNode<T>();
		top=head;
		size=0;
	}
	
	public Stack(){}
	
	@SuppressWarnings("unchecked")
	public void push(T value){
		top.next=new MyNode<>(value);
		top=top.next;
		++size;
	}
	
	@SuppressWarnings("unchecked")
	public T pop(){
		T value=null;
		
		if (size!=0){
			value=top.get();
			MyNode<T> iterator=head;
			while(iterator.next!=top){
				iterator=iterator.next;
			}
			iterator.next=null;
			top=iterator;
			--size;
		}
		
		return value;
	}
	
	public int getLength(){
		return size;
	}
	
	public String toString(){
		if (size==0){
			return null;
		}
		StringBuilder str=new StringBuilder();
		MyNode<T> iterator=head.next;
		while (iterator!=null){
			str.append("->["+iterator.get()+"]");
			iterator=iterator.next;
		}
		str.delete(0, 2);
		return str.toString();
	}

}
